#include <iostream>
#include <cstring>
#include <unistd.h>
#include <fcntl.h>
#include <ctime>
#include <sys/time.h>
#include <cassert>

// 将文件描述符设置为 非阻塞 模式
bool SetNonBlock(int fd)
{
    int fl = fcntl(fd, F_GETFL); // 获取指定文件描述符 fd 的文件状态标志
    if(fl < 0) {
        return false;
    }
    fcntl(fd, F_SETFL, fl | O_NONBLOCK); // 设置文件状态标志为非阻塞

    return true;
}

int main()
{
    while(true) // 实时检测时间信息
    {
        std::cout << "time: " << (unsigned long long)time(NULL) << std::endl;
        struct timeval curtime = {0, 0};
        int n = gettimeofday(&curtime, NULL);
        assert(n == 0); (void)n;
        std::cout << "gettimeofday(): " << curtime.tv_sec << "." << curtime.tv_usec << std::endl;
        sleep(1);
    }   

#if 0
    SetNonBlock(0); // 设置一次非阻塞
    char buffer[1024];
    while(true)
    {
        sleep(1);
        errno = 0;
        // 非阻塞时，以出错形式返回，告知上层：数据未就绪
        ssize_t s = read(0, buffer, sizeof(buffer) - 1); // 0: 标准输入
        if(s > 0) {
            buffer[s-1] = 0;
            std::cout << "echo# " << buffer << " errno[---]" << errno << "error string: " << strerror(errno) << std::endl;
        } else {
            // 若errno为11，意味着是底层数据未就绪，并非出错
            std::cout << "read \"error\" " << "errno: " << errno << "error string: " << strerror(errno) << std::endl;
            if(errno == EWOULDBLOCK || errno == EAGAIN) // 均为11
            {
                std::cout << "当0号fd数据未就绪. try again!" << std::endl;
                continue;
            } 
            else if (errno == EINTR)
            {
                std::cout << "read被信号中断" << std::endl;
                continue;
            }
            else
            {
                // 错误处理
                std::cout << "read error" << std::endl;
            }
        }
    }

#endif
}